package org.timeismoney.payment.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.PropertyFilter;

import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Hibernate;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;

public class JSONHelper {
	public static class IgnoreProxyObj4JSONFilter implements PropertyFilter {

		public boolean apply(Object source, String name, Object value) {
			if (value instanceof HibernateProxy) {
				if (value != null && Hibernate.isInitialized(value)) {
					Object tmp = ((HibernateProxy) value)
							.getHibernateLazyInitializer().getImplementation();
					try {
						BeanUtils.copyProperty(source, name, tmp);
					} catch (Exception e) {
						e.printStackTrace();
					}
					return false;
				}
				return true;
			}
			if (value instanceof LazyInitializer)
				return true;
			if (value instanceof PersistentCollection)
				return true;
			return false;
		}

	}

	public static class DateJsonValueProcessor implements JsonValueProcessor {

		private String				format	= "yyyy-MM-dd HH:mm:ss";
		private SimpleDateFormat	sdf		= new SimpleDateFormat(format);

		public Object processArrayValue(Object value, JsonConfig jsonConfig) {
			return this.process(value);
		}

		public Object processObjectValue(String key, Object value,
				JsonConfig jsonConfig) {
			return this.process(value);
		}

		private Object process(Object value) {
			if (value == null) {
				return "";
			} else if (value instanceof Date)
				return sdf.format((Date) value);
			else {
				return value.toString();
			}
		}
	}
}
